package main
import(
	"net/http"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"regexp"
)
func main(){
	url:="https://mingxing.xianyongjiu.com/20201119/17689_628d5d7c/1000k/hls/index.m3u8"
	downFromM3u8Url(url,"")
}

func downFromM3u8Url(url string,parent string){
     data:=getHttpResponseData(url)
     urls:=getUrls(data)
     for _,urlx:=range urls{
     	fmt.Println(urlx,"开始下载……")
     	fN:=urlx[strings.LastIndex(urlx,`/`)+1:]
     	download(url[:strings.LastIndex(url,`/`)]+`/`+urlx,fN)
     	fmt.Println(urlx,"下载完成")
     }
}

func getUrls(m3u8Content []byte)[]string{
	urls:=[]string{}
	content:=string(m3u8Content)
	lines:=regexp.MustCompile("\r?\n").Split(content,-1)
	for i:=0;i<len(lines);i++{
		if strings.HasPrefix(strings.TrimSpace(lines[i]),`#EXTINF:`){
			i++
			nextLine:=lines[i]
			urls=append(urls,nextLine)
		}
	}
	return urls
}

func download(url string,fileName string){
	if res,err:=http.Get(url);err!=nil{
		panic(url+"下载失败："+err.Error())
	}else{
		defer res.Body.Close()
		data,_:=ioutil.ReadAll(res.Body)
		ioutil.WriteFile(fileName,data,os.ModeAppend)
		fmt.Println(url+" 下载完成")
	}
}

func getHttpResponseData(url string)[]byte{
	if res,err:=http.Get(url);err!=nil{
		panic(url+"下载失败："+err.Error())
	}else{
		defer res.Body.Close()
		data,_:=ioutil.ReadAll(res.Body)
		return data
	}
}